// 给你一棵所有节点为非负值的二叉搜索树，请你计算树中任意两节点的差的绝对值的最小值。
// 思路1，递归，中序遍历，中序遍历的二叉搜索树是有序的
function getMinimumDifference(root) {
    let result = Infinity
    let pre
    function dfs(root) {
        if (!root) {
            return
        }
        dfs(root.left)
        if (pre) {
            result = Math.min(result, Math.abs(Number(pre.val) - Number(root.val)))
        }
        pre = root
        dfs(root.right)
    }
    dfs(root)
    return result
}

function getMinimumDifference2(root) {
    let stack = []
    let cur = root
    let pre
    let result = Infinity
    while (stack.length || cur) {
        if (cur) {
            stack.push(cur)
            cur = cur.left
        } else {
            let node = stack.pop()
            if (pre) {
                result = Math.min(result, Math.abs(Number(pre.val) - Number(node.val)))
            }
            pre = node
            cur = node.right
        }
    }
    return result
}

const root = {
    val: 4,
    left: {
        val: 3,
        left: {
            val: 2,
        },
        right: {
            val: 3.5,
            left: {
                val: 3.1
            }
        },
    },
    right: {
        val: 6,
    },
};

console.log(getMinimumDifference(root))
console.log(getMinimumDifference2(root))